/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package proyecto.web;


import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import proyecto.service.AreaService;
import proyecto.modelo.Area;
import proyecto.excepcion.DAOExcepcion;

/** 
 *
 * @author Administrador
 */
public class AreaController extends MultiActionController {

    public AreaController() {
        //Initialize controller properties here or 
        //in the Web Application Context
        //setCommandClass(MyCommand.class);
        //setCommandName("MyCommandName");
        //setSuccessView("successView");
        //setFormView("formView");
    }

    //@Override
    protected void doSubmitAction(Object command) throws Exception {
        throw new UnsupportedOperationException("Not yet implemented");
    }
    //Use onSubmit instead of doSubmitAction 
    //when you need access to the Request, Response, or BindException objects
    /*
    @Override
    protected ModelAndView onSubmit(
    HttpServletRequest request,
    HttpServletResponse response,
    Object command,
    BindException errors) throws Exception {
    ModelAndView mv = new ModelAndView(getSuccessView());
    //Do something...
    return mv;
    }
     */
    private AreaService areaService;

    public AreaService getAreaService() {
        return areaService;
    }

    public void setAreaService(AreaService areaService) {
        this.areaService = areaService;
    }

    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
        return new ModelAndView("/MantenimientoArea");
    }

    public ModelAndView buscar(HttpServletRequest request, HttpServletResponse response) {
        String nombres = request.getParameter("descripcion");
        try {
            
            Collection<Area> areas = areaService.buscarPorNombre(nombres);

            PrintWriter out = response.getWriter();
            //Construye una tabla con los datos de la lista
            String tabla = doLLenarTabla(areas);
            out.println(tabla);
            out.close();

            request.setAttribute("areas", areas);
        } catch (IOException ex) {
            Logger.getLogger(AreaController.class.getName()).log(Level.SEVERE,
                    null, ex);
        } catch (DAOExcepcion ex) {
            System.err.println(ex.toString());
        }
        return null;
    }

    public ModelAndView nuevo(HttpServletRequest request, HttpServletResponse response) {
        return new ModelAndView("/MantenimientoArea");
    }

    public ModelAndView insertar(HttpServletRequest request, HttpServletResponse response) {
        Area vo = new Area();
        vo.setAre_Codigo(Integer.parseInt(request.getParameter("codigo")));

        vo.setAre_Descripcion(request.getParameter("descripcion"));
        try {
            areaService.insertar(vo);
            
            Collection<Area> areas = areaService.buscarPorNombre("");

            PrintWriter out = response.getWriter();
            //Construye una tabla con los datos de la lista
            String tabla = doLLenarTabla(areas);
            out.println(tabla);
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(AreaController.class.getName()).log(Level.SEVERE,
                    null, ex);
        } catch (DAOExcepcion e) {
            System.err.println(e.toString());
        }
        //buscar( request,  response);
        return new ModelAndView("redirect:/MantenimientoArea.htm");
    }

    public ModelAndView eliminar(HttpServletRequest request, HttpServletResponse response) {
        String codigo = request.getParameter("codigo");
        try {
            areaService.eliminar(Integer.parseInt(codigo));

            Collection<Area> areas = areaService.buscarPorNombre("");

            PrintWriter out = response.getWriter();
            //Construye una tabla con los datos de la lista
            String tabla = doLLenarTabla(areas);
            out.println(tabla);
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(AreaController.class.getName()).log(Level.SEVERE,
                    null, ex);
        } catch (DAOExcepcion ex) {
            System.err.println(ex.toString());
        }
        return new ModelAndView("redirect:/MantenimientoArea.htm");
    }

    public ModelAndView obtener(HttpServletRequest request, HttpServletResponse response) {
        int codigo = Integer.parseInt(request.getParameter("codigo"));
        Area vo;
        try {
            vo = areaService.obtener(codigo);

            //Construye el objeto JSON  a partir del objeto recuperado
            Gson gson = new GsonBuilder().setPrettyPrinting().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
            ArrayList objeto = new ArrayList(0);
            objeto.add(vo);
            String instancia = gson.toJson(objeto);

            PrintWriter out = response.getWriter();
            //Construye un objeto con los datos
            out.println(instancia);
            out.close();

            request.setAttribute("Area", vo);
        } catch (IOException ex) {
            Logger.getLogger(AreaController.class.getName()).log(Level.SEVERE,
                    null, ex);

        } catch (DAOExcepcion e) {
            System.err.println("Error");
        }
        return new ModelAndView("redirect:/MantenimientoArea.htm");
    }

    public ModelAndView actualizar(HttpServletRequest request, HttpServletResponse response) {
        int codigo = Integer.parseInt(request.getParameter("codigo"));
        Area vo = new Area();
        vo.setAre_Codigo(codigo);
        vo.setAre_Descripcion(request.getParameter("descripcion"));
        try {
            areaService.actualizar(vo);
            
            Collection<Area> areas = areaService.buscarPorNombre("");
            
            PrintWriter out = response.getWriter();
            //Construye una tabla con los datos de la lista
            String tabla = doLLenarTabla(areas);
            out.println(tabla);
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(AreaController.class.getName()).log(Level.SEVERE,
                    null, ex);
        } catch (DAOExcepcion e) {
            System.err.println("Error");
        }
        return new ModelAndView("redirect:/MantenimientoArea.htm");
    }

    private String doLLenarTabla(Collection<Area> areas) {

        int codigo = 0;
        String desc = "";

        String cabecera = "<table class='datos'>" +
                "<tr class='Estilo9 Estilo12'>" +
                "<th>C&oacute;digo</th>" +
                "<th>Descripci&oacute;n</th>" +
                "<th>&nbsp;</th>" +
                "<th>&nbsp;</th></tr>";
        String celdas = "";

        for (Area a : areas) {
            codigo = a.getAre_Codigo();
            desc = a.getAre_Descripcion();
            celdas = celdas +
                    "<tr>" +
                    "<td ><span class=\"Estilo12\">" + codigo + "</span></td>" +
                    "<td ><span class=\"Estilo12\">" + desc + "</span></td>" +
                    "<td><a onclick=\"return areaObtener('" + codigo + "');\"><img src=\"imagenes/b_edit.gif\" alt=\"Editar\" title=\"Editar\" /></a></td>" +
                    "<td><a onclick=\"return areaEliminar('" + codigo + "');\"><img src=\"imagenes/delete.png\" alt=\"Editar\" title=\"Editar\" /></a></td>" +
                    "</tr>";
        }
        String tabla = cabecera + celdas + "</table>";

        return tabla;
    }

    public ModelAndView listar(HttpServletRequest request, HttpServletResponse response) {
        String nombres = request.getParameter("descripcion");

        try {

            Collection<Area> areas = areaService.buscarPorNombre(nombres);

            PrintWriter out = response.getWriter();
            //Construye una tabla con los datos de la lista
            String tabla = doLLenarCombo(areas);
            out.println(tabla);
            out.close();

            request.setAttribute("areas", areas);
        } catch (IOException ex) {
            Logger.getLogger(CargoController.class.getName()).log(Level.SEVERE,
                    null, ex);
        } catch (DAOExcepcion ex) {
            System.err.println(ex.toString());
        }
        return null;
    }

    private String doLLenarCombo(Collection<Area> areas) {

        int codigo = 0;
        String desc = "";

        String combo = "<select name=\"cboArea\" id=\"cboArea\">";

        for (Area a : areas) {
            codigo = a.getAre_Codigo();
            desc = a.getAre_Descripcion();
            combo = combo +
                    "<option value=\"" + codigo + "\">" + desc + "</option>";
        }

        combo = combo + "</select>";

        return combo;
    }
}
